var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require("fs");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var ObjectID = require('mongodb').ObjectID;
var app = express();
var multer = require("multer")
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/panda");
var db = mongoose.connection;
db.on("error",()=>{ console.log("连接失败")});
db.on("open",()=>{console.log("连接成功")});

var UserSchame = mongoose.Schema({
    phone:{type:String},
    name:{type:String,default:""},
    imgpath:{Type:String},
    password:{type:String},
    role:{type:String,default:"管理员"},
    address:{type:String,default:" "},
    email:{type:String,default:" "},
});
var GoodsSchame = mongoose.Schema({
    name:{type:String},
    desc:{type:String,default:"暂无描述"},
    price:{type:Number},
    gtype:{type:String,default:"食品"},
    stock:{type:Number,default:0},
    imgpath:{type:String}
});

var OrderSchame = mongoose.Schema({

    name:{type:String},
    clientid:{type:mongoose.SchemaTypes.ObjectID},
    phone:{type:String,default:" "},
    price:{type:Number,default:0},
    address:{type:String,default:" "},
    state:{type:String,default:"已下单"},
    ctime:{type:Date,default:Date.now()},
    shops:{type:[{name:String,price:Number,sid:String,num:Number,gtype:String}]}
});

var Guestchame = mongoose.Schema({
    name:{type:String},
    phone:{type:String,default:" "},
    company:{type:String,default:"保密"},
    price:{type:Number,default:0},
    ctype:{type:String,default:"普通客户"},
    address:{type:String,default:" "}
});
var SettingSchame = mongoose.Schema({
    userid:{type:mongoose.SchemaTypes.ObjectID},
    less:{type:Number,default:20},
    large:{type:Number,default:50},
    level:{type:Number,default:120},
});

var Users = mongoose.model("users",UserSchame,"users");
var Goods = mongoose.model("goods",GoodsSchame,"goods");
var Ordes = mongoose.model("orders",OrderSchame,"orders");
var Guests = mongoose.model("guests",Guestchame,"guests");
var Setting = mongoose.model("settings",SettingSchame,"settings");

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.listen(8009)
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {

        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});
app.post("/zuce",function (req,res) {

    let phone = req.body.phone;
    let pass = req.body.password;
    Users.findOne({phone:phone},function (err,doc) {
        if(!err){
            if(doc==null){
                Users.create({ phone:phone,password:pass },function (err,doc) {
                    if(!err){
                        sendMsg("OK",res,doc);
                    }else{
                        sendMsg("NO",res,doc);
                    }
                });
            }else{
                sendMsg("NO",res,doc);
            }
        }
    });
});


app.post("/denglu",function (req,res) {

    let phone = req.body.phone;
    let pass = req.body.password;
    Users.findOne({ phone:phone,password:pass },function (err,doc) {
        if(!err){
            if(doc.length!=0)
              sendMsg("OK",res,doc);
        }else{
              sendMsg("NO",res,doc);
        }
    });
});

app.post("/userinfo",function (req,res) {

    let _id = req.body._id;
    Users.findOne({_id:ObjectID(_id)},function (err,doc) {
        if(!err){
          sendMsg("OK",res,doc);
        }else{
          sendMsg("NO",res,doc);
        }
    });
});




app.post("/updateuser",function (req,res) {

    let _id = req.body._id;
    let name = req.body.name;
    let phone = req.body.phone;
    let address = req.body.address;
    let imgpath = req.body.imgpath;
    let usd = req.body.usd;
    let email = req.body.email;
    let pasword = req.body.password;
    if(usd==0){

        Users.updateOne({_id:ObjectID(_id)},{name:name,phone:phone,address:address,imgpath:imgpath,email:email},function (err,doc) {
            if(!err){

                sendMsg("OK",res,doc);
            }else{
                sendMsg("NO",res,doc);
            }
        });
    }else{
        Users.updateOne({_id:ObjectID(_id)},{name:name,phone:phone,address:address,imgpath:imgpath,pasword:pasword,email:email},function (err,doc) {
            if(!err){
                sendMsg("OK",res,doc);
            }else{
                sendMsg("NO",res,doc);
            }
        });
    }
});

app.post("/alluser",function (req,res) {

    Users.find({},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/deleteuser",function (req,res) {

    let _id = req.body._id;
    Users.deleteOne({_id:ObjectID(_id)},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});


function  sendMsg(status,res,doc){
    let tag = 0;
    if(status=="OK"){
        tag = 1;
    }
    res.json({st:tag,doc:doc});
}

//订单
app.post("/addorder",function (req,res) {

    let _id = req.body._id;
    let name = req.body.name;
    let phone = req.body.phone;
    let address = req.body.address;
    let company = req.body.company;
    let price = req.body.price;
    let total = req.body.total;
    let level = req.body.level;
    let shops =  req.body.shops;
    let ctype = total>=level ?"VIP客户" : "普通客户";
    if(_id=="0"){ //新客户订单 //先添加客户
        console.log("OOK");
        Guests.create({name:name,phone:phone,address:address,company:company,price:price,ctype:ctype},function (err,doc) {
            if(!err){
                Ordes.create({name:name,clientid:ObjectID(doc._id),phone:phone,address:address,shops:shops,price:price},function (err,doc2) {
                    if(!err){
                      sendMsg("OK",res,doc2);
                    }else {
                      sendMsg("NO",res,doc2);
                    }
                });
            }else{
                sendMsg("NO",res,doc);
            }
        });
    }else{ //就客户的订单

        Guests.updateOne({_id:ObjectID(_id)},{$inc:{price:price},ctype:ctype},function (err,doc) {
            if(!err){
                Ordes.create({name:name,clientid:ObjectID(doc._id),phone:phone,address:address,shops:shops,price:price},function (err,doc2) {
                    if(!err){
                        sendMsg("OK",res,doc2);
                    }else {
                        sendMsg("NO",res,doc2);
                    }
                });
            }else{
             sendMsg("NO",res,doc);
            }
        });
    }

});

app.post("/allorder",function (req,res) {
    Ordes.find({},function (err,doc) {

        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});
app.post("/orderprice",function (req,res) {

    Ordes.aggregate([
        {
            $group:{
              _id:"",
              total:{$sum:"$price"}
            }
        }
    ],function (err,doc) {

        if(!err){
          sendMsg("OK",res,doc);
        }else{
          sendMsg("NO",res,doc);
        }
    });
});
app.post("/orderinfo",function (req,res) {
    let _id = req.body._id;
    Ordes.findOne({_id:ObjectID(_id)},function (err,doc) {

        if(!err){
           sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});
app.post("/deleteorder",function (req,res) {

    let _id = req.body._id;
    Ordes.deleteOne({_id:ObjectID(_id)},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/updateorder",function (req,res) {

    let _id = req.body._id;
    let name = req.body.name;
    let phone = req.body.phone;
    let address = req.body.address;
    let price = req.body.price;
    let shops = req.body.shops;
    let state = req.body.state;
    Ordes.updateOne({_id:ObjectID(_id)},{name:name,phone:phone,address:address,price:price,shops:shops,state:state},function (err,doc) {
        if(!err){
          sendMsg("OK",res,doc);
        }else{
         sendMsg("NO",res,doc);
        }
    });
});

app.post("/ordertype",function (req,res) {
    let state = req.body.state;
    Ordes.find({state:state},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});


//商品
app.post("/allshop",function (req,res) {

   Goods.find({},function (err,doc) {
       if(!err){
           sendMsg("OK",res,doc);
       }else{
           sendMsg("NO",res,doc);
       }
   });
});
app.post("/deleteshop",function (req,res) {

    let _id = req.body._id;
    Goods.deleteOne({_id:ObjectID(_id)},function (err,doc) {

        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/updateshop",function (req,res) {

    let _id = req.body._id;
    let name  = req.body.name;
    let price = req.body.price;
    let desc = req.body.desc;
    let imgpath = req.body.imgpath;
    let stock = req.body.stock;
    let ctype = req.body.ctype;
    Goods.updateOne({_id:ObjectID(_id)},{name:name,price:price,imgpath:imgpath,desc:desc,stock:stock,ctype:ctype},function (err,doc) {

        if(!err){
            sendMsg("OK",res,doc);
        }else{
           sendMsg("NO",res,doc);
        }
    });
});

app.post("/addshop",function (req,res) {
    let name = req.body.name;
    let gtype = req.body.gtype;
    let price = req.body.price;
    let stock = req.body.stock;
    let desc = req.body.desc;
    let imgpath = req.body.imgpath;

    Goods.findOne({name:name},function (err,doc) {

        if(!err&&doc==null){
            Goods.create({name:name,gtype:gtype,price:price,stock:stock,desc:desc,imgpath:imgpath},function (err,doc) {
                if(!err){
                    sendMsg("OK",res,doc);
                }else{
                    sendMsg("NO",res,doc);
                }
            });
        }else{
            sendMsg("NO",res,doc);
        }
    });

});
app.post("/shop",function (req,res) {
    let _id = req.body._id;
    Goods.findOne({_id:ObjectID(_id)},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/updatestock",function (req,res) {
    let _id = req.body._id;
    let stock = req.body.stock
    Goods.updateOne({_id:ObjectID(_id)},{stock:stock},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/stockany",function (req,res) {

    Goods.aggregate([{
        $group:{
         _id:"$gtype",
         totalPop:{$sum:"$stock"},
        },
    }],function (err,doc) {

        if(!err){
           sendMsg("OK",res,doc);
        }else{
          sendMsg("NO",res,doc);
        }
    });
});


///客户
app.post("/allclient",function (req,res) {

    Guests.find({},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});
app.post("/addclient",function (req,res) {

    let name = req.body.name;
    let phone = req.body.phone;
    let address = req.body.address;
    let ctype = req.body.ctype;
    let company = req.body.company;

    Guests.create({name:name,phone:phone,address:address,ctype:ctype,company:company},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/updateclient",function (req,res) {

    let _id = req.body._id;
    let name = req.body.name;
    let phone = req.body.phone;
    let address = req.body.address;
    let ctype = req.body.ctype;
    let company = req.body.company;
    Guests.updateOne({_id:ObjectID(_id)},{name:name,phone:phone,address:address,ctype:ctype,company:company},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/deleteclient",function (req,res) {

    let _id = req.body._id;
    Guests.deleteOne({_id:ObjectID(_id)},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});


app.post("/client",function (req,res) {

    let _id = req.body._id;
    Guests.findOne({_id:ObjectID(_id)},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/clienttype",function (req,res) {

    let ctype = req.body.ctype;
    Guests.find({ctype:ctype},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});




//库存
app.post("/calcstock",function (req,res) {
    let type = req.body.type;
    let val = req.body.val;
    //大于
    if(type==1){
        console.log("OOK?")
        console.log(val);
        Goods.find({stock:{$lt:val}},function (err,doc) {
            if(!err){
                sendMsg("OK",res,doc);
            }else{
                sendMsg("NO",res,doc);
            }
        });
    }else{
      //小于
      Goods.find({stock:{$gt:val}},function (err,doc) {

          if(!err){
              sendMsg("OK",res,doc);
          }else{
              sendMsg("NO",res,doc);
          }
      });
    }
});

app.post("/betstock",function (req,res) {

    let less = req.body.less;
    let lager = req.body.lager;
    Goods.find({stock:{ $gt: less, $lt: lager}},function (err,doc) {

        if(!err){
         sendMsg("OK",res,doc);
        }else{
          sendMsg("NO",res,doc);
        }
    });
});

//设置
app.post("/setting",function (req,res) {

    let userid = req.body._id;

    Users.findOne({_id:ObjectID(userid)},function (err,doc) {
       console.log(doc);
        if(!err){
            if(doc.role!="管理员"){
                console.log("tun hthththt∂ß")
                Setting.findOne({userid:ObjectID(userid)},function (err2,doc2) {
                    if(!err2){
                        console.log("KKKKKK")
                        console.log(doc2);
                        if(doc2==null){
                            console.log("rhe sss")
                            Setting.create({userid:ObjectID(userid)},function (err,doc3) {
                                console.log(doc3);
                                sendMsg("OK",res,doc3);
                            });
                        }else{
                            sendMsg("OK",res,doc2);
                        }

                    }else{
                        sendMsg("NO",res,doc);
                    }
                });
            }
        }else{

        }
    });

});

app.post("/updatesetting",function (req,res) {

    let userid = req.body._id;
    let less = req.body.less;
    let lager = req.body.lager;
    Goods.updateOne({userid:ObjectID(userid)},{less:less,lager:lager},function (err,doc) {
        if(!err){
            sendMsg("OK",res,doc);
        }else{
            sendMsg("NO",res,doc);
        }
    });
});

app.post("/uploadimg",multer({
    dest:"./public"
}).single('file'),function (req,res,next) {

    if(req.file.length==0){
        res.json({status:-4});
    }else{

        let file = req.file;
        let fileInfo = {};
        fs.renameSync('./public/'+file.filename,'./public/'+file.originalname);
        fileInfo.mimeType = file.mimetype;
        fileInfo.originalname = file.originalname;
        fileInfo.size = file.size;
        fileInfo.path = file.path;
        res.set({'content-type': 'application/json; charset=utf-8'})
        res.json({status:4,result:fileInfo.originalname})
    }
});

//数据统计

app.post("/delayany",function (req,res) {

    Ordes.aggregate([
        {
            $group:{
              _id:"$shops.name",
              num_tutorial:{$sum:1},
              count:{$sum:'$shops.num'}
            },
        },
    ],function (err,doc) {

        if(!err){
            sendMsg("OK",res,doc);
        }
    })
});

module.exports = app;
